/* ==============================================================================
*
*   Copyright (c) 2010, Pierre Favier
*   All rights reserved.
*
*   NTasking is free software: you can redistribute it and/or modify it
*   under the terms of the GNU General Public License as published by the
*   Free Software Foundation.
*
*   Redistribution and use in source and binary forms, with or without
*   modification, are permitted provided that the following conditions
*   are met:
*
*   -   Redistributions of source code must retain the above copyright notice,
*       this list of conditions and the following disclaimer.
*
*   -   Redistributions in binary form must reproduce the above
*       copyright notice, this list of conditions and the following
*       disclaimer in the documentation and/or other materials
*       provided with the distribution.
*
*   THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESS OR IMPLIED
*   WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
*   OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
*   DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS
*   BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
*   EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
*   TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
*   DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
*   ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
*   TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
*   THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
*   SUCH DAMAGE.
*
* ============================================================================== */

using System;
using NTasking.ValidationTests.ACATS_3_0.Support;
using NUnit.Framework;
using Rhino.Mocks;

namespace NTasking.ValidationTests.ACATS_3_0.C9
{

    [TestFixture(Description = "")]
    public class C9740010 : ValidationTest
    {

        internal class TransactioCancelled : Exception { }


        internal enum KeyEnum
        {
            None,
            Cancel,
            Deposit,
            Withdraw
        }


        internal class ATMCardType
        {
            public int Number { get; set; }
            public int Pin { get; set; }
        }


        internal class ATMKeybordTask : ValidationTestTask
        {

            internal class Suicide : Exception {}


            [Entry]
            internal Action CancelPressed { get; private set; }


            internal ATMKeybordTask(IValidationTestResult result)
                : base(result)
            {}


            protected override void Body()
            {
                KeyEnum keyPressed = KeyEnum.None;

                throw new Suicide();

                Accept(CancelPressed, () =>
                {
                    // Accept statement executed
                    Result.TestFailed();
                });
            }
            protected override void Exception(Exception ex)
            {
                if (!(ex is Suicide))
                    // Unexpected Exception in ATMKeyboardTask
                    Result.TestFailed();
            }

        }


        private static void ValidateCard(ATMCardType card, IValidationTestResult result)
        {
            // Abortable part was executed.
            result.TestFailed();
        }


        private static void PerformTransaction(ATMCardType card, IValidationTestResult result)
        {
            // Exception not re-raised immediately following
            // asynchronous select
            result.TestFailed();
        }


        [Test(Description =
            "Check that the abortable part of an asynchronous select statement " +
            "is not started if the triggering statement is a task entry call to " +
            "a task that has already terminated." +
            "\n" +
            "Check that Tasking_Error is properly propagated to the asynchronous " +
            "select statement and thus the sequence of statements of the triggering " +
            "a task that has already terminated." +
            "\n" +
            "Check that Tasking_Error is re-raised immediately following the" +
            "asynchronous select.")]
        public void Test()
        {
            IValidationTestResult result = Mocks.DynamicMock<IValidationTestResult>();

            ATMKeybordTask keyboard = null;
            ATMCardType card = new ATMCardType();
            bool TC_Tasking_Error_Handled = false;

            Ada.Declare(() =>
            {
                keyboard = new ATMKeybordTask(result);

                // Setup test expectations

                Expect.Call(result.TestFailed).Repeat.Never();

                Mocks.ReplayAll();
            },
            Begin: () =>
            {
                // Start test execution

                // Ensure the task is already completed before calling
                while (!keyboard.Terminated)
                    Ada.Delay(Impdef.MinimumTaskSwitch);

                //
                // Asynchronous select is tested here
                //

                Ada.Select(s =>
                    s.Call(keyboard.CancelPressed)().
                    // Should not be executed.
                    Then(() =>
                    {
                        throw new TransactioCancelled();
                    }).
                ThenAbort(() =>
                {
                    // Since the triggering call is not queued the abortable part
                    // should not be executed.
                    ValidateCard(card, result);
                }));

                // The propagated exception is re-raised here
                
                // Should not be reached.
                PerformTransaction(card, result);
            },
            Exception: (ex) =>
            {
                if (ex is TransactioCancelled)
                {
                    // Triggering alternative sequence of statements
                    // executed
                    result.TestFailed();
                }
                else if (ex is TaskingError)
                {
                    // This is the expected test path
                    TC_Tasking_Error_Handled = true;
                }
                else
                {
                    // Wrong exception raise
                    result.TestFailed();
                }
                return false;
            });

            if (!TC_Tasking_Error_Handled)
                // Tasking_Error not properly propagated
                result.TestFailed();
        }

    }

}
